package org.unei.multiprocessor.sharememory;

import org.unei.multiprocessor.ThreadID;

public class AtomicMRMWRegister <T> implements Register<T>{

	private StampedValue<T>[] a_table;
	public AtomicMRMWRegister(int capacity,T init){
		a_table=(StampedValue<T>[])new StampedValue[capacity];
		StampedValue<T> value=new StampedValue<T>(init);
		for(int j=0;j<a_table.length;j++)
			a_table[j]=value;
	}
	
	@Override
	public T read() {
		StampedValue<T> max=(StampedValue<T>) StampedValue.MIN_VALUE;
		for(int i=0;i<a_table.length;i++)
			max=StampedValue.max(max, a_table[i]);
		return max.value;
	}

	@Override
	public void write(T v) {
		int me=ThreadID.get();
		StampedValue<T> max=(StampedValue<T>) StampedValue.MIN_VALUE;
		for(int i=0;i<a_table.length;i++)
			max=StampedValue.max(max, a_table[i]);
		
		a_table[me]=new StampedValue(max.stamp+1,v);
	}

}
